package com.da.lon.wang.xlg.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.da.lon.wang.xlg.bean.PhoneConfirmBean;
import com.da.lon.wang.xlg.bean.RegistBean;
import com.da.lon.wang.xlg.constants.PreferencesConfig;
import com.da.lon.wang.xlg.constants.XLGConstants;
import com.da.lon.wang.xlg.constants.XLGConstants.MethodName;
import com.da.lon.wang.xlg.http.HttpLoader;
import com.da.lon.wang.xlg.http.HttpLoader.OnWebLoadListener;
import com.da.lon.wang.xlg.util.PreferenceUtils;
import com.da.lon.wang.xlg.util.Utils;
import com.da.lon.wang.xlg.util.XLGDataUtils;
import com.umeng.analytics.MobclickAgent;

import net.tsz.afinal.http.AjaxParams;

/**
 * 手机验证
 */
public class PhoneConfirmActivity extends BaseActivity implements OnClickListener {

    private Button timeBtn;
    private int sumTime = 60; // 倒计时初试时间
    private EditText verificationEdit;
    private EditText passwordEdit;
    private EditText passwordAgainEdit;
    private Button nextBtn;
    private String phone;
    private TextView phoneTv;
    private TextView kefuTv;
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    sumTime--;
                    if (sumTime > 0) {
                        timeBtn.setText("重新发送" + "(" + sumTime + ")");
                        handler.sendEmptyMessageDelayed(1, 1 * 1000);
                    } else {
                        timeBtn.setText("重新发送");
                        timeBtn.setBackgroundColor(Color.parseColor("#cccccc"));
                        timeBtn.setEnabled(true);
                    }
                    break;

                default:
                    break;
            }

        }

        ;
    };

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xlg_phone_confirm);
        initView();
    }

    private void initView() {
        phone = getIntent().getStringExtra("phone");
        ImageButton back = (ImageButton) findViewById(R.id.ouka_phoneconfirm_left);
        back.setOnClickListener(this);
        timeBtn = (Button) findViewById(R.id.time);
        timeBtn.setText("重新发送" + "(" + sumTime + ")");
        timeBtn.setEnabled(false);
        timeBtn.setOnClickListener(this);
        handler.sendEmptyMessageDelayed(1, 1 * 1000);
        verificationEdit = (EditText) findViewById(R.id.verification);
        passwordEdit = (EditText) findViewById(R.id.password);
        passwordAgainEdit = (EditText) findViewById(R.id.password_again);
        nextBtn = (Button) findViewById(R.id.next);
        nextBtn.setOnClickListener(this);
        phoneTv = (TextView) findViewById(R.id.phone);
        phoneTv.setText(phone);
        kefuTv = (TextView) findViewById(R.id.kefu);
        kefuTv.setOnClickListener(this);
    }

    /**
     * 手机验证
     */

    private void phoneConfirm() {
        try {
            String url = XLGConstants.URL + XLGConstants.URL_HEAD + MethodName.PHONE_CONFIRM;
            HttpLoader<PhoneConfirmBean> httpLoader = new HttpLoader<PhoneConfirmBean>(this, url, PhoneConfirmBean.class);
            AjaxParams params = new AjaxParams();
            params.put("phone", phone);
            params.put("token",
                    XLGDataUtils.encrypt2MD5(XLGConstants.API + XLGConstants.SECRET + MethodName.PHONE_CONFIRM));
            params.put("device_type", "1");

            httpLoader.setManagerListener(new OnWebLoadListener<PhoneConfirmBean>() {

                @Override
                public void OnStart() {
                    showDialog("发送中");

                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                    Toast.makeText(PhoneConfirmActivity.this, "验证发送失败", Toast.LENGTH_SHORT).show();

                }

                @Override
                public void onSuccess(PhoneConfirmBean t) {
                    dismissDialog();
                    if (t != null && t.getCode().equals("000000")) {
                        Toast.makeText(PhoneConfirmActivity.this, "验证已发送", Toast.LENGTH_SHORT).show();
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_VERIFICATION,
                                t.getResult().getPhone_vercode());
                    } else {
                        Toast.makeText(PhoneConfirmActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                }
            });

            httpLoader.loadData(params);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }

    /**
     * 注册用户
     */

    private void registAccount() {
        try {
            String url = XLGConstants.URL + XLGConstants.URL_HEAD + MethodName.REGIST;
            HttpLoader<RegistBean> httpLoader = new HttpLoader<RegistBean>(this, url, RegistBean.class);
            AjaxParams params = new AjaxParams();
            params.put("username", phone);
            params.put("password", XLGDataUtils.encrypt2MD5(passwordEdit.getText().toString()));
            params.put("device_type", "1");
            params.put("token", XLGDataUtils.encrypt2MD5(XLGConstants.API + XLGConstants.SECRET + MethodName.REGIST));
            params.put("phone_vercode", verificationEdit.getText().toString());

            httpLoader.setManagerListener(new OnWebLoadListener<RegistBean>() {

                @Override
                public void OnStart() {
                    showDialog();

                }

                @Override
                public void OnError(String error) {
                    dismissDialog();
                    Toast.makeText(PhoneConfirmActivity.this, "注册失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(RegistBean t) {
                    dismissDialog();
                    if (t != null && t.getCode().equals("000000")) {
                        Toast.makeText(PhoneConfirmActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
                        handler.removeMessages(1);
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_KEY,
                                t.getResult().getUser_key());
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_ID, t.getResult().getId());
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_NAME,
                                t.getResult().getUserName());
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_BALANCE,
                                t.getResult().getBalance());
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.HEAD_LOG,
                                t.getResult().getHead_log());
                        PreferenceUtils.getInstance().SetSettingString(PreferencesConfig.USER_TYPE,
                                t.getResult().getUser_type());
                        MyApplication.getInstance().clearActivityList();
                        Intent intent = new Intent(PhoneConfirmActivity.this, HomeActivity.class);
                        startActivity(intent);
                        // 绑定个推别名
                        // PushManager.getInstance().bindAlias(PhoneConfirmActivity.this,
                        // "xlg" + t.result.id);

                        //发送广播注册别名
                        Intent intentalias = new Intent();
                        intent.setAction(XLGConstants.TAGANDALIAS_RECEIVED_ACTION);
                        PhoneConfirmActivity.this.sendBroadcast(intentalias);

                        Utils.updateUserInfo(PhoneConfirmActivity.this);
                        if (MyApplication.getIs_skulist_enter_capture() == 1) {
                            startActivity(new Intent(PhoneConfirmActivity.this,
                                    HomeActivity.class));
                            MyApplication
                                    .setIs_skulist_enter_capture(0);
                            MyApplication.getInstance().getSkulist_activity().finish();
                        }


                        finish();
                    } else {
                        Toast.makeText(PhoneConfirmActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                }
            });

            httpLoader.loadData(params);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ouka_phoneconfirm_left:
                finish();
                break;
            case R.id.time:
                phoneConfirm();
                break;
            case R.id.next:
                if (TextUtils.isEmpty(verificationEdit.getText().toString())
                        || TextUtils.isEmpty(passwordEdit.getText().toString())
                        || TextUtils.isEmpty(passwordAgainEdit.getText().toString())) {
                    Toast.makeText(this, getString(R.string.input_empty), Toast.LENGTH_SHORT).show();
                } else if (!passwordEdit.getText().toString().equals(passwordAgainEdit.getText().toString())) {
                    Toast.makeText(this, getString(R.string.password_unsame), Toast.LENGTH_SHORT).show();
                } else if (passwordEdit.getText().toString().length() > 15
                        || passwordEdit.getText().toString().length() < 6) {
                    Toast.makeText(this, getString(R.string.password_length_error), Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isDigitsOnly(passwordEdit.getText().toString())) {
                    Toast.makeText(this, getString(R.string.digits_all), Toast.LENGTH_SHORT).show();
                } else {
                    registAccount();
                }
                break;
            case R.id.kefu:
                // WebViewUtil.startChat(this,"","","","","","","","");
                break;
            default:
                break;
        }

    }
}
